<template>
  <div
    class="field-control-wrapper"
    :class="{ 'is-selected': isSelected }"
    :style="wrapperStyle"
    @mousedown.stop="startDrag"
  >
    <div class="control-content">
      <template v-if="control.type === 'text-input'">
        <el-input
          :placeholder="control.properties.placeholder"
          :model-value="control.value"
          @input="onValueChange"
          :disabled="!isEditableMode"
        />
      </template>
      <template v-else-if="control.type === 'textarea'">
        <el-input
          type="textarea"
          :placeholder="control.properties.placeholder"
          :model-value="control.value"
          @input="onValueChange"
          :disabled="!isEditableMode"
          :rows="control.properties.rows || 2"
        />
      </template>
      <template v-else-if="control.type === 'select'">
        <el-select
          :placeholder="control.properties.placeholder"
          :model-value="control.value"
          @change="onValueChange"
          :disabled="!isEditableMode"
          style="width: 100%;"
        >
          <el-option
            v-for="option in control.properties.options"
            :key="option.value"
            :label="option.label"
            :value="option.value"
          />
        </el-select>
      </template>
      <template v-else-if="control.type === 'radio'">
        <el-radio-group
          :model-value="control.value"
          @change="onValueChange"
          :disabled="!isEditableMode"
        >
          <el-radio 
            v-for="option in control.properties.options" 
            :key="option.value" 
            :label="option.value"
          >
            {{ option.label }}
          </el-radio>
        </el-radio-group>
      </template>
      <template v-else-if="control.type === 'checkbox'">
        <el-checkbox
          :model-value="control.value ?? control.properties.checked"
          @change="onValueChange"
          :disabled="!isEditableMode"
        >
            {{ control.properties.label }}
        </el-checkbox>
      </template>
      <template v-else-if="control.type === 'checkbox-group'">
        <el-checkbox-group
          :model-value="control.value || []"
          @change="onValueChange"
          :disabled="!isEditableMode"
        >
          <el-checkbox 
            v-for="option in control.properties.options" 
            :key="option.value" 
            :label="option.value"
          >
            {{ option.label }}
          </el-checkbox>
        </el-checkbox-group>
      </template>
      <template v-else-if="control.type === 'signature'">
        <div class="signature-display">
          <img v-if="control.value" :src="control.value" alt="Signature" class="placed-signature-img" />
          <span v-else class="placeholder-text">{{ control.properties.label }} (点击签署)</span>
          <el-button v-if="isEditableMode" size="small" @click.stop="openSignaturePad">签署</el-button>
        </div>
      </template>
      </div>

    <template v-if="isSelected && isEditorMode">
      <div class="resizer top-left" @mousedown.stop="startResize('tl')"></div>
      <div class="resizer top-right" @mousedown.stop="startResize('tr')"></div>
      <div class="resizer bottom-left" @mousedown.stop="startResize('bl')"></div>
      <div class="resizer bottom-right" @mousedown.stop="startResize('br')"></div>
      <div class="resizer top" @mousedown.stop="startResize('t')"></div>
      <div class="resizer bottom" @mousedown.stop="startResize('b')"></div>
      <div class="resizer left" @mousedown.stop="startResize('l')"></div>
      <div class="resizer right" @mousedown.stop="startResize('r')"></div>
    </template>
  </div>

  <el-dialog
    v-model="showSignatureDialog"
    title="签署"
    width="600px"
    :close-on-click-modal="false"
  >
    <SignaturePad @signed="handleSignature" @clear="clearSignature" />
    <template #footer>
      <el-button @click="showSignatureDialog = false">取消</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, defineProps, defineEmits } from 'vue';
import SignaturePad from './SignaturePad.vue'; // 假设您有这个组件

const props = defineProps({
  control: Object,
  isSelected: Boolean,
  isEditableMode: {
    type: Boolean,
    default: true, // 在编辑模式下允许编辑，否则只显示值
  },
  isEditorMode: { // 区分编辑器模式和运行时模式
      type: Boolean,
      default: true,
  }
});

const emit = defineEmits([
  'update-position',
  'update-size',
  'update-control-properties', // 用于运行时更新值
]);

const showSignatureDialog = ref(false);

const wrapperStyle = computed(() => {
  // 如果控件有坐标比例且window.pdfInfo可用，使用比例定位
  let x = props.control.x;
  let y = props.control.y;
  let width = props.control.width;
  let height = props.control.height;
  
  if (props.control.coordinateRatio && window.pdfInfo && window.pdfInfo.pageInfo && window.pdfInfo.pageInfo[props.control.page]) {
    const pageInfo = window.pdfInfo.pageInfo[props.control.page];
    
    // 根据页面信息和坐标比例计算精确位置
    if (pageInfo && pageInfo.width && pageInfo.height) {
      x = pageInfo.width * props.control.coordinateRatio.x;
      y = pageInfo.height * props.control.coordinateRatio.y;
      width = pageInfo.width * props.control.coordinateRatio.width;
      height = pageInfo.height * props.control.coordinateRatio.height;
    }
  }
  
  return {
    position: 'absolute',
    left: `${x}px`,
    top: `${y}px`, 
    width: `${width}px`,
    height: `${height}px`,
    cursor: props.isEditorMode ? 'grab' : 'auto',
    zIndex: props.isSelected ? 100 : 1, // 选中时置顶
  };
});

const onValueChange = (newValue) => {
  // 更新控件的 value 属性，这个 value 是用户实际填写的数据
  // prop 的 control 是 reactive 的，可以直接修改
  props.control.value = newValue;
  // 也可以emit事件通知父组件更新，但props.control本身就是reactive的，直接修改即可
  // emit('update-control-properties', { id: props.control.id, value: newValue });
};

// ======================= Dragging Logic =======================
let isDragging = false;
let startX = 0;
let startY = 0;
let initialX = 0;
let initialY = 0;

const startDrag = (event) => {
  if (!props.isEditorMode) return;
  isDragging = true;
  startX = event.clientX;
  startY = event.clientY;
  initialX = props.control.x;
  initialY = props.control.y;
  document.addEventListener('mousemove', drag);
  document.addEventListener('mouseup', stopDrag);
};

const drag = (event) => {
  if (!isDragging) return;
  const dx = event.clientX - startX;
  const dy = event.clientY - startY;

  const newX = initialX + dx;
  const newY = initialY + dy;

  // 获取页面信息以更新坐标比例
  if (window.pdfInfo && window.pdfInfo.pageInfo && window.pdfInfo.pageInfo[props.control.page]) {
    const pageInfo = window.pdfInfo.pageInfo[props.control.page];
    
    // 更新坐标比例
    if (pageInfo && pageInfo.width && pageInfo.height) {
      props.control.coordinateRatio = {
        x: newX / pageInfo.width,
        y: newY / pageInfo.height,
        width: props.control.width / pageInfo.width,
        height: props.control.height / pageInfo.height
      };
    }
  }

  emit('update-position', props.control.id, newX, newY, props.control.page);
};

const stopDrag = () => {
  isDragging = false;
  document.removeEventListener('mousemove', drag);
  document.removeEventListener('mouseup', stopDrag);
};

// ======================= Resizing Logic =======================
let isResizing = false;
let resizeDirection = '';
let startResizeX = 0;
let startResizeY = 0;
let initialWidth = 0;
let initialHeight = 0;
let initialLeft = 0;
let initialTop = 0;

const startResize = (direction, event) => {
  if (!props.isEditorMode) return;
  isResizing = true;
  resizeDirection = direction;
  startResizeX = event.clientX;
  startResizeY = event.clientY;
  initialWidth = props.control.width;
  initialHeight = props.control.height;
  initialLeft = props.control.x;
  initialTop = props.control.y;

  document.addEventListener('mousemove', resize);
  document.addEventListener('mouseup', stopResize);
};

const resize = (event) => {
  if (!isResizing) return;
  const dx = event.clientX - startResizeX;
  const dy = event.clientY - startResizeY;

  let newWidth = initialWidth;
  let newHeight = initialHeight;
  let newX = initialLeft;
  let newY = initialTop;

  switch (resizeDirection) {
    case 'tl': // Top-left
      newX = initialLeft + dx;
      newY = initialTop + dy;
      newWidth = initialWidth - dx;
      newHeight = initialHeight - dy;
      break;
    case 'tr': // Top-right
      newY = initialTop + dy;
      newWidth = initialWidth + dx;
      newHeight = initialHeight - dy;
      break;
    case 'bl': // Bottom-left
      newX = initialLeft + dx;
      newWidth = initialWidth - dx;
      newHeight = initialHeight + dy;
      break;
    case 'br': // Bottom-right
      newWidth = initialWidth + dx;
      newHeight = initialHeight + dy;
      break;
    case 't': // Top
      newY = initialTop + dy;
      newHeight = initialHeight - dy;
      break;
    case 'b': // Bottom
      newHeight = initialHeight + dy;
      break;
    case 'l': // Left
      newX = initialLeft + dx;
      newWidth = initialWidth - dx;
      break;
    case 'r': // Right
      newWidth = initialWidth + dx;
      break;
  }

  // 最小尺寸限制
  newWidth = Math.max(newWidth, 10);
  newHeight = Math.max(newHeight, 10);

  // 如果尺寸改变，更新x,y确保左上角不变
  if (resizeDirection.includes('l') && newWidth !== initialWidth - dx) {
    newX = initialLeft + initialWidth - newWidth;
  }
  if (resizeDirection.includes('t') && newHeight !== initialHeight - dy) {
    newY = initialTop + initialHeight - newHeight;
  }

  emit('update-position', props.control.id, newX, newY, props.control.page);
  emit('update-size', props.control.id, newWidth, newHeight);
};

const stopResize = () => {
  isResizing = false;
  document.removeEventListener('mousemove', resize);
  document.removeEventListener('mouseup', stopResize);
};

// ======================= Signature Logic (for signature type) =======================
const openSignaturePad = () => {
  showSignatureDialog.value = true;
};

const handleSignature = (signatureBase64) => {
  props.control.value = signatureBase64;
  showSignatureDialog.value = false;
};

const clearSignature = () => {
  props.control.value = null;
  showSignatureDialog.value = false;
};
</script>

<style scoped>
.field-control-wrapper {
  border: 1px dashed transparent;
  display: flex;
  align-items: center;
  justify-content: center;
  position: absolute;
  box-sizing: border-box;
  overflow: hidden; /* 防止内部内容超出边界 */
  background-color: rgba(255, 255, 255, 0.7); /* 半透明背景 */
  transition: border-color 0.1s;
}

.field-control-wrapper:hover {
  border-color: #409eff;
}

.field-control-wrapper.is-selected {
  border: 1px solid #409eff;
  outline: 1px dashed #409eff; /* 选中时显示轮廓 */
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

.control-content {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 2px;
  box-sizing: border-box;
}

/* 针对 Element Plus 组件的样式调整 */
.field-control-wrapper .el-input,
.field-control-wrapper .el-checkbox,
.field-control-wrapper .el-select,
.field-control-wrapper .el-radio-group,
.field-control-wrapper .el-checkbox-group {
  width: 100%;
  height: 100%;
}
.field-control-wrapper .el-input :deep(.el-input__wrapper) {
  height: 100%;
  padding: 0 5px;
}
.field-control-wrapper .el-checkbox :deep(.el-checkbox__label) {
  font-size: 12px; /* 调整字体大小 */
  white-space: nowrap;
}
.field-control-wrapper .el-checkbox {
  align-items: center;
  justify-content: center;
}

/* 多选框组样式 */
.field-control-wrapper .el-checkbox-group {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  overflow-y: auto;
}

/* 单选框组样式 */
.field-control-wrapper .el-radio-group {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  overflow-y: auto;
}
.field-control-wrapper .el-radio {
  margin-right: 0;
  margin-bottom: 5px;
}
.field-control-wrapper .el-radio :deep(.el-radio__label) {
  font-size: 12px;
}

/* 下拉选择样式 */
.field-control-wrapper .el-select :deep(.el-input__wrapper) {
  height: 100%;
}

/* 多行文本样式 */
.field-control-wrapper .el-input.el-input--textarea :deep(.el-input__wrapper) {
  height: auto;
}
.field-control-wrapper .el-textarea :deep(.el-textarea__inner) {
  resize: none;
  height: 100%;
}

.signature-display {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  font-size: 12px;
  color: #909399;
}
.placed-signature-img {
  max-width: 90%;
  max-height: 90%;
  object-fit: contain;
}
.placeholder-text {
  text-align: center;
  line-height: 1.2;
}

/* Resizers */
.resizer {
  position: absolute;
  width: 8px;
  height: 8px;
  background: #409eff;
  border: 1px solid #fff;
  z-index: 101; /* 确保在控件之上 */
}

.resizer.top-left { top: -4px; left: -4px; cursor: nwse-resize; }
.resizer.top-right { top: -4px; right: -4px; cursor: nesw-resize; }
.resizer.bottom-left { bottom: -4px; left: -4px; cursor: nesw-resize; }
.resizer.bottom-right { bottom: -4px; right: -4px; cursor: nwse-resize; }
.resizer.top { top: -4px; left: calc(50% - 4px); cursor: ns-resize; width: 16px; }
.resizer.bottom { bottom: -4px; left: calc(50% - 4px); cursor: ns-resize; width: 16px; }
.resizer.left { left: -4px; top: calc(50% - 4px); cursor: ew-resize; height: 16px; }
.resizer.right { right: -4px; top: calc(50% - 4px); cursor: ew-resize; height: 16px; }
</style>